package com.hzit.search.util;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.api.RemoteManagerService;
import com.ruoyi.system.api.domain.Item;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@SpringBootTest
public class ESUtil {
	@Autowired
	private ElasticsearchClient client;
	@Autowired
	private RemoteManagerService managerService;

	/**
	 * 1. 创建索引库，并同时添加映射
	 */
	@Test
	public void test01() throws IOException {
		client.indices().create(idx -> idx.index("item")
				.mappings(mappingBuilder -> mappingBuilder
						.properties("title", propertyBuilder -> propertyBuilder.text(textProperty -> textProperty.analyzer("ik_smart").searchAnalyzer("ik_smart")))
						// .properties("title",propertyBuilder->propertyBuilder.text(textProperty->textProperty))
						.properties("price", propertyBuilder -> propertyBuilder.float_(floatProperty -> floatProperty))
						.properties("category", propertyBuilder -> propertyBuilder.keyword(keywordProperty -> keywordProperty))
						.properties("brand", propertyBuilder -> propertyBuilder.keyword(brandProperty -> brandProperty))
				));
	}

	/**
	 * 2. 将远程查询到的数据放到索引库中
	 */
	@Test
	public void test02() throws IOException {
		//2.1  从远程查询出数据
		List<Item> items = getItems();
		//2.2 循环将数据放到索引库中
		BulkRequest.Builder br = new BulkRequest.Builder();
		for (Item item : items) {
			br.operations(op -> op.index(idx -> idx
							.index("item")
							.id(item.getId() + "")
							.document(item)
			));
		}
		 //2.3 执行批量操作
		client.bulk(br.build());
		System.out.println("完成添加到索引库操作。");
	}

	// 从远程查询数据库
	private List<Item> getItems() {
		R<List<Item>> r = managerService.findItems();
		List<Item> itemList = r.getData();
		List<Item> items = new ArrayList<>();
		for (Item item : itemList) {
			if(item.getStatus().equals("1")){
				String spec = item.getSpec();
				Map map = JSON.parseObject(spec, Map.class);
				item.setSpecMap(map);
				items.add(item);
			}
		}
		return items;
	}

	//3. 根据id删除item项
	@Test
	public void test03() throws IOException {
		client.delete(dq -> dq.index("item").id("1369287"));
	}
}
